package com.wzz.common.animation;

import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.Transformation;

/**
 * com.hymobile.common.animation.RollXYAnimatione
 * @author 梁天刚</br>
 * created at 2011-11-30 上午9:43:07</br>
 * 半成品，和其他动画组合使用有问题
 */
public class RollXYAnimatione extends Animation {

  private Camera camera;
  private float fromXDegree, toXDegree;
  private float fromYDegree, toYDegree;
  private float centerX, centerY, centerXValue, centerYValue;
  private int centerXType, centerYType;

  public RollXYAnimatione() {
    super();
    initialise();
  }

  public RollXYAnimatione(Context context, AttributeSet attrs) {
    super(context, attrs);
    initialise();
  }

  private void initialise() {
    camera = new Camera();
  }

  /**
   * 反转X轴
   * @param fromDegree
   * @param toDegree
   */
  public void rollX(float fromDegree, float toDegree) {
    fromXDegree = fromDegree;
    toXDegree = toDegree;
  }

  /**
   * 反转Y轴
   * @param fromDegree
   * @param toDegree
   */
  public void rollY(float fromDegree, float toDegree) {
    fromYDegree = fromDegree;
    toYDegree = toDegree;
  }

  /**
   * 设置反转中心
   * @param xType should be one of Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF,
   *          or Animation.RELATIVE_TO_PARENT.
   * @param xValue
   * @param yType should be one of Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF,
   *          or Animation.RELATIVE_TO_PARENT.
   * @param yValue
   */
  public void setCenter(int xType, float xValue, int yType, float yValue) {
    centerXType = xType;
    centerXValue = xValue;
    centerYType = yType;
    centerYValue = yValue;
  }

  /*
   * @see android.view.animation.Animation#initialize(int, int, int, int)
   */
  @Override
  public void initialize(int width, int height, int parentWidth, int parentHeight) {
    super.initialize(width, height, parentWidth, parentHeight);
    centerX = resolveSize(centerXType, centerXValue, width, parentWidth);
    centerY = resolveSize(centerYType, centerYValue, height, parentHeight);
  }

  protected void applyTransformation(float interpolated, Transformation t) {
    camera.save();
    camera.rotateX(fromXDegree + (toXDegree - fromXDegree) * interpolated);
    camera.rotateY(fromYDegree + (toYDegree - fromYDegree) * interpolated);
    Matrix matrix = t.getMatrix();
    camera.getMatrix(matrix);
    matrix.preTranslate(-centerX, -centerY);
    matrix.postTranslate(centerX, centerY);
    camera.restore();
  }

}
